package com.gxa.saas.portal.oauth2;

import com.alibaba.druid.util.StringUtils;
import com.gxa.saas.core.utils.JwtUtil;
import com.gxa.saas.portal.service.hhyservice.ShopLoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private ShopLoginService shopLoginService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("===========doGetAuthenticationInfo==========================");
        //根据收到的token 解密 进行判断是否正确，正确就取出用户id，将用户对象查出来。
        String accessToken = (String)token.getPrincipal();
        String username = JwtUtil.getUsername(accessToken);
        if (StringUtils.isEmpty(username)){
            System.out.println("登录凭证错误");
            throw new IncorrectCredentialsException("登录凭证错误");
        }
        if(JwtUtil.isTokenExpired(accessToken)){
            System.out.println("登录已过期，请重新登录");
            throw new IncorrectCredentialsException("登录已过期，请重新登录");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(),token.getCredentials(), getName());
        return info;
    }
}
